package com.chap6;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * <code>SyncDemo</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-03-16 14:06
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class SyncDemo {
    private static int counter = 0;
    private final static Lock lock = new ReentrantLock();

    public static void increment(){
        counter++;
    }


    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                increment();
            }
        },"t1") ;

        Thread t2 = new Thread(()->{
            for (int i = 0; i < 5000; i++) {
                increment();
            }
        },"t2") ;
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        //t1 t2都执行完，主线程才执行
        System.out.println(counter);
        /*
        counter 预期值：10000
        不是10000，代码有线程安全问题。
        最蛋疼的问题是每次结果不一样，完全不可控。
        */
    }
}
